import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { apiConf } from '@conf/api.conf';
import { STColumn } from '@delon/abc/st';
import { _HttpClient } from '@delon/theme';
import { NzImageService } from 'ng-zorro-antd/image';
import { NzModalService } from 'ng-zorro-antd/modal';
import { UsermanageService } from '../../../services/usercenter.service';

@Component({
  selector: 'app-usercenter-components-driver-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.less'],
  providers: [DatePipe]
})
export class UserCenterComponentsDriverDetailComponent implements OnInit {
  detailData: any;
  userDetail: any;
  contencarModel: any;
  facetext: any;
  faceStatus: any = 0;
  userIdentityDetail: any = {};
  tempalateUserIdentityDetail = { ...this.userIdentityDetail };
  driverDetail: any = {
    licenseNo: '',
    driverModel: [],
    validStartTime: '',
    validEndTime: '',
    signingOrganization: '',
    certificatePhotoWatermark: ''
  };
  tempalateDriverData = { ...this.driverDetail };
  licenseDetail: any = {
    licenseNo: '',
    validStartTime: '',
    validEndTime: '',
    certificatePhotoWatermark: '',
    regionCode: ''
  };
  tempalateLicenseDetail = { ...this.licenseDetail };
  columns: STColumn[] = [
    { title: '企业名称', className: 'text-center', index: 'enterpriseName' },
    { title: '项目名称', className: 'text-center', index: 'projectName' },
    { title: '角色', className: 'text-center', index: 'roleName' }
  ];
  carList: any = [];

  @ViewChild('redectModal', { static: false })
  redectModal!: any;
  @ViewChild('rejectedDriverModal', { static: false })
  rejectedDriverModal!: any;
  adressCodeList: any = [];
  billEvaluateList: any = [];
  approvalOpinion = '';
  bankList: any[] = [];
  isEditUser = false;
  isEditDriver = false;

  uploadURl = apiConf.waterFileUpload;
  disabledUpload = false;
  constructor(
    private nzModalService: NzModalService,
    public service: UsermanageService,
    public route: ActivatedRoute,
    private datePipe: DatePipe,
    private nzImageService: NzImageService
  ) {}

  ngOnInit() {
    console.log(this.route.snapshot.queryParams);
    
    this.initData();
    this.initDetailByCode();
  }
  initData() {
    // 获取司机头部信息
    this.service.request(this.service.$api_get_user_detail, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.userDetail = res;
      }
    });
    this.service.request(this.service.$api_getDictValue, { dictKey: 'driverModel' }).subscribe(res => {
      if (res) {
        this.contencarModel = res;
      }
    });
    // 获取人脸识别结果
    this.service.request(this.service.$api_getFaceFlowQuery, { id: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.faceStatus = res.status;
        if (res.status == 4) {
          this.facetext = res.failReason;
        }
      }
    });
    // 获取用户个人信息
    this.service.request(this.service.$api_get_user_identity, { id: this.route.snapshot.params.id }).subscribe(res => {
      if (res) {
        this.userIdentityDetail = res;
        this.tempalateUserIdentityDetail = { ...this.userIdentityDetail };
      }
    });
    // 获取驾驶证信息
    this.service.request(this.service.$api_get_driver_license, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
      if (res?.id) {
        Object.assign(res, { driverModel: res.driverModel ? res.driverModel.split(',') : [] });
        this.driverDetail = res;

        this.tempalateDriverData = { ...this.driverDetail };
      }
    });
    // 获取从业资格证信息
    this.service.request(this.service.$api_get_driver_practice_seniority, { appUserId: this.route.snapshot.params.id }).subscribe(res => {
      if (res?.id) {
        this.licenseDetail = res;
        this.tempalateLicenseDetail = { ...this.licenseDetail };
      }
    });
    // 获取载具信息
    this.service.request(this.service.$api_get_driver_car_license, { appUserId: [this.route.snapshot.params.id] }).subscribe(res => {
      if (res) {
        this.carList = res;
      }
    });
    // 获取评价信息
    this.service
      .request(this.service.$api_get_driver_billEvaluate, { passiveUserId: this.route.snapshot.params.id }, 'POST', false)
      .subscribe(res => {
        if (res) {
          this.billEvaluateList = res;
        }
      });

    // 获取用户银行信息
    this.service
      .request(this.service.$api_get_user_bank_list, {
        roleId: this.route.snapshot.params.id
      })
      .subscribe(res => {
        if (res) {
          this.bankList = res;
        }
      });
  }

  /** 启用/冻结司机 */
  userAction(status: number) {
    this.nzModalService.warning({
      nzTitle: status === 1 ? '确定启用该司机吗？' : '确定冻结该司机吗？',
      nzContent: status === 1 ? '启用后，该司机将恢复正常使用功能，请再次确认！' : '冻结后，司机将被限制使用，无法登陆，请谨慎操作！',
      nzOnOk: () => {
        this.service
          .request(this.service.$api_lock_or_free_user, {
            appUserId: [this.userDetail.appUserId],
            freezeOrResume: !!!status,
            pageName: '司机详情',
            telephone: this.userDetail.phone
          })
          .subscribe(res => {
            if (res) {
              this.service.msgSrv.success('操作成功');
            }
            this.initData();
          });
      }
    });
  }

  /** 审核通过个人信息 */
  approveUser() {
    this.nzModalService.confirm({
      nzTitle: '审核通过',
      nzContent: `是否确认通过(姓名:${this.userIdentityDetail.name})审核`,
      nzOnOk: () => {
        this.adjuctUser({ auditStatus: 0, auditType: 0, identityId: this.userIdentityDetail?.id }, '审核通过');
      }
    });
  }

  /** 驳回个人信息 */
  rejectedUser() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.redectModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          this.service.msgSrv.warning('请填写备注');
          return false;
        }
        this.adjuctUser(
          {
            auditStatus: 1,
            auditType: 0,
            identityId: this.userIdentityDetail?.id,
            certificationOpinions: this.approvalOpinion
          },
          '审核驳回成功'
        );
        return;
      }
    });
  }

  /** 审核通过驾驶员信息 */
  approveDriver() {
    
    this.nzModalService.confirm({
      nzTitle: '审核通过',
      nzContent: `<p>驾驶证号：${this.driverDetail?.licenseNo}</p><p>从业资格证号：${this.licenseDetail?.licenseNo}</p><p>是否确认通过审核`,
      nzOnOk: () => {
        this.adjuctDriverLicense(
          {
            approvalStatus: 20,
            appUserId: this.userDetail?.appUserId
          },
          '审核成功'
        );
      }
    });
  }
 
  /** 驳回驾驶员信息 */
  rejectedDriver() {
    this.approvalOpinion = '';
    this.nzModalService.create({
      nzTitle: '审核驳回',
      nzContent: this.rejectedDriverModal,
      nzOnOk: () => {
        if (!this.approvalOpinion) {
          return false;
        }
        this.adjuctDriverLicense(
          {
            approvalStatus: 30,
            appUserId: this.userDetail?.appUserId,
            approvalOpinion: this.approvalOpinion
          },
          '审核驳回成功'
        );
        return;
      }
    });
  }

  /** 个人信息审核 */
  private adjuctUser(params: any, msg: string) {
    this.service.request(this.service.$api_approve_identity, { ...params }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success(msg);
      }
      this.initData();
    });
  }

  /** 驾驶员审核 */
  private adjuctDriverLicense(params: any, msg: string) {
    this.service.request(this.service.$api_approve_driver_license, { ...params }).subscribe(res => {
      if (res) {
        this.service.msgSrv.success(msg);
      }
      this.initData();
    });
  }

  /**
   * 开启修改
   * @param type 修改类型
   */
  ratify(type: number) {
    if (type) {
      this.isEditDriver = true;
    } else {
      this.isEditUser = true;
    }
  }

  /**
   * 需求修改
   * @param type 修改类型
   */
  reset(type: number) {
    if (type) {
      this.driverDetail = { ...this.tempalateDriverData };
      this.licenseDetail = { ...this.tempalateLicenseDetail };
      this.isEditDriver = false;
    } else {
      this.userIdentityDetail = { ...this.tempalateUserIdentityDetail };
      this.isEditUser = false;
    }
  }
  /*
   * 根据地区code查询地区详情
   * code：请求参数
   * type：参数 name：获取省市区名称，fullcode：获取省市区code
   * num：参数 1：第一个地区选择，2：第二个地区选择
   */
  initDetailByCode() {
    // 根据地区code查询地区详情
    this.service.request(this.service.$api_get_region_by_code, { regionCode: '' }).subscribe((res: any) => {
      this.adressCodeList = res;
    });
  }

  /**
   * 修改驾驶证，从业资格证信息
   */
  saveDriver() {
    const driverDetail = this.driverDetail;
    const licenseDetail = this.licenseDetail;
    // console.log(this.driverDetail);
    if (driverDetail.validStartTime && driverDetail.validEndTime) {
      let validStartTime = driverDetail.validStartTime;
      let validEndTime = driverDetail.validEndTime;
      if (typeof driverDetail.validStartTime === 'string') {
        validStartTime = new Date(driverDetail.validStartTime);
      }
      if (typeof driverDetail.validEndTime === 'string') {
        validEndTime = new Date(driverDetail.validEndTime);
      }
      if (validStartTime?.getTime() >= validEndTime?.getTime()) {
        this.service.msgSrv.warning('结束时间必须大于开始时间');
        return;
      }
    }
    if (
      !driverDetail.licenseNo ||
      !driverDetail.driverModel ||
      !driverDetail.validStartTime ||
      !driverDetail.signingOrganization ||
      !driverDetail.certificatePhotoWatermark
    ) {
      this.service.msgSrv.warning('请完善驾驶证信息');
      return;
    }

    if (!licenseDetail.licenseNo || !licenseDetail.validStartTime || !licenseDetail.certificatePhotoWatermark) {
      this.service.msgSrv.warning('请完善从业资格证信息');
      return;
    }

    const params: any = {
      userId: this.route.snapshot.params.id,
      mobile: this.userDetail?.phone,
      appUserId: driverDetail.appUserId || this.route.snapshot.params.id,
      userDriverLicenseDTO: {
        appUserId: driverDetail?.appUserId || this.route.snapshot.params.id,
        certificatePhoto: driverDetail.certificatePhoto,
        certificatePhotoWatermark: driverDetail.certificatePhotoWatermark,
        driverModel: driverDetail.driverModel.join(','),
        id: driverDetail.id,
        licenseNo: driverDetail.licenseNo,
        signingOrganization: driverDetail.signingOrganization,
        validEndTime:
          driverDetail.validEndTime?.length === 10
            ? driverDetail.validEndTime
            : this.datePipe.transform(driverDetail.validEndTime, 'yyyy-MM-dd'),
        validStartTime:
          driverDetail.validStartTime?.length === 10
            ? driverDetail.validStartTime
            : this.datePipe.transform(driverDetail.validStartTime, 'yyyy-MM-dd')
      },
      userPracticeSeniorityDTO: {
        appUserId: licenseDetail.appUserId || this.route.snapshot.params.id,
        approvalStatus: licenseDetail.approvalStatus,
        certificatePhoto: licenseDetail.certificatePhoto,
        certificatePhotoWatermark: licenseDetail.certificatePhotoWatermark,
        id: licenseDetail.id,
        licenseNo: licenseDetail.licenseNo,
        regionCode: licenseDetail.regionCode,
        validEndTime:
          licenseDetail.validEndTime?.length === 10
            ? licenseDetail.validEndTime
            : this.datePipe.transform(licenseDetail.validEndTime, 'yyyy-MM-dd'),
        validStartTime:
          licenseDetail.validStartTime?.length === 10
            ? licenseDetail.validStartTime
            : this.datePipe.transform(licenseDetail.validStartTime, 'yyyy-MM-dd')
      }
    };
    // if (licenseDetail.approvalStatus && licenseDetail.licenseNo && licenseDetail.regionCode) {
    //   params.userPracticeSeniorityDTO = {
    //     appUserId: licenseDetail.appUserId || this.route.snapshot.params.id,
    //     approvalStatus: licenseDetail.approvalStatus,
    //     certificatePhoto: licenseDetail.certificatePhoto,
    //     certificatePhotoWatermark: licenseDetail.certificatePhotoWatermark,
    //     id: licenseDetail.id,
    //     licenseNo: licenseDetail.licenseNo,
    //     regionCode: licenseDetail.regionCode,
    //     validEndTime:
    //       licenseDetail.validEndTime?.length === 10
    //         ? licenseDetail.validEndTime
    //         : this.datePipe.transform(licenseDetail.validEndTime, 'yyyy-MM-dd'),
    //     validStartTime:
    //       licenseDetail.validStartTime?.length === 10
    //         ? licenseDetail.validStartTime
    //         : this.datePipe.transform(licenseDetail.validStartTime, 'yyyy-MM-dd')
    //   };
    // }
    console.log(params);
    this.service.request(this.service.$api_update_driver_license, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改成功');
        this.isEditDriver = false;
        this.initData();
      }
    });
  }

  saveUser() {
    const userIdentity = this?.userIdentityDetail;
    const params = {
      certificateNumber: userIdentity?.certificateNumber,
      certificatePhotoBack: userIdentity?.certificatePhotoBack,
      certificatePhotoBackWatermark: userIdentity?.certificatePhotoBackWatermark,
      certificatePhotoFront: userIdentity?.certificatePhotoFront,
      certificatePhotoFrontWatermark: userIdentity?.certificatePhotoFrontWatermark,
      certificateType: userIdentity?.certificateType,
      handCertificate: userIdentity?.handCertificate,
      id: userIdentity?.id,
      name: userIdentity?.name,
      souceType: userIdentity?.souceType,
      sourceAppId: userIdentity?.sourceAppId,
      tenantId: userIdentity?.tenantId,
      userId: userIdentity?.userId,
      validEndTime:
        userIdentity?.validEndTime?.length === 10
          ? userIdentity?.validEndTime
          : this.datePipe.transform(userIdentity?.validEndTime, 'yyyy-MM-dd'),
      validStartTime:
        userIdentity?.validStartTime?.length === 10
          ? userIdentity?.validStartTime
          : this.datePipe.transform(userIdentity?.validStartTime, 'yyyy-MM-dd')
    };
    this.service.request(this.service.$api_update_driver_identity, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('修改成功');
        this.isEditUser = false;
        this.initData();
      }
    });
  }

  changeUpload({ file, fileList, type }: any, data: any, key: string, key2: string, id: string) {
    if (type === 'success') {
      data[key] = file.response.data?.fullFileWatermarkPath;
      data[key2] = file.response.data?.fullFilePath;
      if (id === 'certificateBackFront' || id === 'certificateBack') {
        this.checkIdCard(file.response.data?.fullFilePath, id === 'certificateBackFront' ? 'front' : 'back', 0);
      }
    }
  }

  showImg(url: any) {
    this.nzImageService.preview([{ src: url }]);
  }

  deleteImg(data: any, key: string, key2: string) {
    this.nzModalService.warning({
      nzTitle: '是否确认删除该图片',
      nzOnOk: () => {
        this.disabledUpload = true;
        data[key] = '';
        data[key2] = '';
        setTimeout(() => {
          this.disabledUpload = false;
        }, 100);
      }
    });
  }

  goBack() {
    window.history.go(-1);
  }

  // 识别身份证 参数isFront：front-正面、back-背面；type：0-申请人身份证，1-法定代表人身份证
  checkIdCard(imgurl: any, isFront: string, type: number) {
    const params = {
      idCardUrl: imgurl,
      side: isFront
    };
    this.service.request(this.service.$api_ocr_recognize_id_card, params).subscribe(res => {
      if (res) {
        // 企业管理员证件照
        if (type === 0) {
          if (isFront === 'front') {
            // 正面
            if (res.name) {
              this.userIdentityDetail.name = res.name;
            }
            if (res.number) {
              this.userIdentityDetail.certificateNumber = res.number;
            }
          }
        }
      }
    });
  }
}
